package com.shaw.workrecord.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shaw.workrecord.dto.DintWordGroup;
import com.shaw.workrecord.entity.PageRequest;
import com.shaw.workrecord.entity.PageResponse;
import com.shaw.workrecord.exception.CustomerException;
import com.shaw.workrecord.mapper.DintWordGroupMapper;
import com.shaw.workrecord.pojo.game.request.DintWordGroupAddRequest;
import com.shaw.workrecord.pojo.game.request.DintWordGroupEditRequest;
import com.shaw.workrecord.pojo.game.response.DintWordGroupResponse;
import com.shaw.workrecord.service.IDintWordGroupService;
import com.shaw.workrecord.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author jiangjunhui
 * @description
 * @date 2022/9/15 16:34
 */
@Service
public class DintWordGroupServiceImpl extends ServiceImpl<DintWordGroupMapper, DintWordGroup> implements IDintWordGroupService {
    /**
     * 获取词组分页列表
     *
     * @param pageRequest
     * @return 分页结果
     */
    @Override
    public PageResponse<DintWordGroupResponse> getWordPage(PageRequest pageRequest) {
        LambdaQueryWrapper<DintWordGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.select().orderByDesc(DintWordGroup::getCreateTime);
        Page<DintWordGroup> page = new Page<>(pageRequest.getPageIndex(), pageRequest.getPageSize());
        Page<DintWordGroup> p = baseMapper.selectPage(page, wrapper);
        return PageUtils.toPageResponse(p, DintWordGroupResponse.class);
    }

    /**
     * 新增词组
     *
     * @param request 词组请求对象
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addWord(DintWordGroupAddRequest request) {
        DintWordGroup dintWordGroup = BeanUtil.copyProperties(request, DintWordGroup.class);
        int result = baseMapper.insert(dintWordGroup);
        return result > 0;
    }

    /**
     * 编辑词组
     *
     * @param request 词组请求对象
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editWord(DintWordGroupEditRequest request) {
        DintWordGroup dintWordGroup = BeanUtil.copyProperties(request, DintWordGroup.class);
        int result = baseMapper.updateById(dintWordGroup);
        return result > 0;
    }

    /**
     * 删除词组
     *
     * @param id id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWord(Long id) {
        DintWordGroup dintWordGroup = baseMapper.selectById(id);
        if (dintWordGroup == null) {
            throw new CustomerException("词组不存在，无法删除");
        }
        int result = baseMapper.deleteById(id);
        return result > 0;
    }
}
